package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserOrderMapper;
import com.eco.fanliapp.dao.AppUserRewardSetupMapper;
import com.eco.fanliapp.dao.SyChannelGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.OrderController;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.OrderNewScheme;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.TbkOrderGetInfo.NTbkOrderDataBean;
import com.eco.fanliapp.vo.job.*;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.google.common.base.Joiner;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TaoBaoIntegralOrderServiceImpl implements ITaoBaoIntegralOrderService {

    private static final Logger log = LoggerFactory.getLogger(TaoBaoIntegralOrderServiceImpl.class);

    @SuppressWarnings({"unused", "rawtypes"})
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private IAppOrderIntegralService iAppOrderIntegralService;
    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private IGoodsFreeService goodsFreeService;
    @Autowired
    private IAppUserRedRewardService IAppUserRedRewardService;
    @Autowired
    private OrderController orderController;
    @Autowired
    private ITaoBaoService taobaoService;

    @Autowired
    private IAppGoodsService iAppGoodsService;

    @Autowired
    private IAppUserSearchHistoryService appUserSearchHistoryService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private FindItemIdUtils taoBaoUtils;

    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;

    @Autowired
    private AppUserRewardSetupMapper appUserRewardSetupMapper;

    /**
     * Eco API
     * 拉取付款订单
     *
     * @param session        淘客的授\权session来查订单
     * @param startTime      下单时间
     * @param pageNo         第几页 默认1，1~100
     * @param tkStatus       订单状态1: 全部订单，3：订单结算，12：订单付款， 13：订单失效，14：订单成功； 订单查询类型为‘结算时间’时，只能查订单结算状态
     * @param orderCountType 订单数据统计类型，1: 2方订单，2: 3方订单，如果不设置，或者设置为1，表示2方订单
     * @param orderQueryType 订单查询类型，创建时间“create_time”，或结算时间“settle_time”。当查询渠道或会员运营订单时，建议入参创建时间“create_time”进行查询
     * @param orderScene     订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1，通过设置订单场景类型，媒体可以查询指定场景下的订单信息，例如不设置，或者设置为1，表示查询常规订单，常规订单包含淘宝客所有的订单数据，含渠道，及会员运营订单，但不包含3方分成，及维权订单
     * @return https://open.taobao.com/api.htm?docId=38078&docType=2
     */
    @Override
    @Async("myTaskAsyncPool")
    public void getPayOrderDetail(String session, String startTime, String endTime, long pageNo, long tkStatus, long orderCountType,
                                  String orderQueryType, long orderScene, int type, String positionIndex) {
        try {
            //淘宝客获取订单信息
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            //数据封装
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            //判断是否有订单
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();
                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {
                    try {
                        //处理单个付款订单
                        this.dealOrderInfo(order, "pay");
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("付款订单处理出错" + e.getMessage());
                    }
                }
                //判断是否存在下一页
                if (info.getData().getHasNext()) {
                    getPayOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus, orderCountType, orderQueryType, orderScene, type, positionIndex);
                }
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (type == 0) {
                this.countLauncherPay.countDown();
            }
        }
        return;
    }

    /**
     * 获取失效订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       13
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Override
    @Async("myTaskAsyncPool")
    public void getFailOrderDetail(String session, String startTime, String endTime, long pageNo,
                                   long tkStatus, long orderCountType, String orderQueryType, long orderScene, int type, String positionIndex) {

        try {
            //获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            log.info("获取到失效数据：{}", str);
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info != null && info.isSuccess() && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {
                    try {
                        boolean flag = this.dealOrderInfo(order, "fail");
                        if (!flag) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("失效订单处理出错" + e.getMessage());
                        continue;
                    }
                }
                //判断是否存在下一页
                if (info.getData().getHasNext()) {
                    getFailOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus, orderCountType, orderQueryType, orderScene, type, positionIndex);
                }
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherFail.countDown();
            }
        }
        return;

    }


    /**
     * 获取成功订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       14
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Override
    @Async("myTaskAsyncPool2")
    public void getSuccOrderDetail(String session, String startTime, String endTime, long pageNo,
                                   long tkStatus, long orderCountType, String orderQueryType, long orderScene, int type, String positionIndex) {

        try {
            //获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    try {
                        boolean flag = this.dealOrderInfo(order, "success");
                        if (!flag) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("完成订单处理出错" + e.getMessage());
                        continue;
                    }
                }
                //判断是否存在下一页
                if (info.getData().getHasNext()) {
                    getSuccOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus, orderCountType, orderQueryType, orderScene, type, positionIndex);
                }
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherDone.countDown();
            }
        }
        return;

    }


    /**
     * 获取结算订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       3
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Override
    @Async("myTaskAsyncPool2")
    public void getSettleOrderDetail(String session, String startTime, String endTime, long pageNo, long tkStatus, long orderCountType,
                                     String orderQueryType, long orderScene, int type, String positionIndex) {

        try {
            //获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();
                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {
                    try {
                        boolean flag = this.dealOrderInfo(order, "settle");
                        if (!flag) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("结算订单处理出错" + e.getMessage());
                        continue;
                    }
                }
                if (info.getData().getHasNext()) {
                    getSettleOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus,
                            orderCountType, orderQueryType, orderScene, type, positionIndex);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherSuccess.countDown();
            }
        }
        return;
    }

    /**
     * 订单信息处理
     *
     * @param order
     * @param type
     * @return
     */
    public boolean dealOrderInfo(TbkScOrderDetailsGetResponse.PublisherOrderDto order, String type) throws Exception {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000L * 60;
        //获取锁
        if (!redisLockService.lock(order.getTradeId() + "doOrderDetailFromTBK", startTimes + "")) {
            return false;
        }

        log.info(type + "处理订单数据：{}", JSON.toJSONString(order));

        //关联用户
        AppUser appUser = UserMainNew(order);
        AppOrderIntegral appOrderIntegral = OrderIntegralMainNew(order, appUser);

        //查询商品
        AppGoods appGoods = getAppgoods(appOrderIntegral.getItemId().toString(), appOrderIntegral);

        //判断免单并插入订单信息-app_order_detail
        appOrderIntegral = this.dealOrderInfoStep1(appUser, appOrderIntegral, appGoods, type);
        //是未绑定订单就结束
        if (appOrderIntegral == null) {
            return false;
        }
        return true;
    }

    /**
     * 存订单信息
     *
     * @param appUser
     * @param appOrderIntegral
     * @param type           0结束 1完成订单插入（判断来源） 4判断免单完成分佣 2 完成红包 3完成任务
     * @return
     */
    public AppOrderIntegral dealOrderInfoStep1(AppUser appUser, AppOrderIntegral appOrderIntegral, AppGoods appGoods, String type) {

        //判断是否是预售订单
        boolean preparePayOrder = isPreparePayOrder(appOrderIntegral);

        //数据库中查询该订单
        AppOrderIntegral appOrderIntegralDatabase = iAppOrderIntegralService.selectAppOrderIntegralByTradeId(appOrderIntegral.getTradeId());
        if (appOrderIntegralDatabase != null) {
            appOrderIntegral.setBinding(appOrderIntegralDatabase.getBinding());
            appOrderIntegral.setBindingTime(appOrderIntegralDatabase.getBindingTime());
            appOrderIntegral.setDeleted(appOrderIntegralDatabase.getDeleted());

            appOrderIntegral.setTableCreateTime(appOrderIntegralDatabase.getTableCreateTime());
            appOrderIntegral.setGoodFrees(appOrderIntegralDatabase.getGoodFrees());
            appOrderIntegral.setItemPic(appOrderIntegralDatabase.getItemPic());
            appOrderIntegral.setFanliMoney(appOrderIntegralDatabase.getFanliMoney());
            appOrderIntegral.setBuySource(appOrderIntegralDatabase.getBuySource());
            appOrderIntegral.setEnabled(appOrderIntegralDatabase.getEnabled());
        }
        //设置商品的图片
        appOrderIntegral.setItemPic(appGoods == null ? "" : appGoods.getItempic());
        if (appOrderIntegral.getItemPic() == null) {
            appOrderIntegral.setItemPic("http:" + appOrderIntegral.getItemImg());
        }

        if (StringUtils.isEmpty(appUser)) {
            log.info(type + "订单关联不到用户,order={}itemId={}relationID={}", appOrderIntegral.getTradeId(), appOrderIntegral.getItemId(), appOrderIntegral.getRelationId());
            //如果没有关联到人，不记录渠道
            appOrderIntegral.setBinding(0);
            int i = iAppOrderIntegralService.insertAppOrderIntegral(appOrderIntegral);
            return null;
        } else {
            if (appOrderIntegralDatabase == null) {
                //查询免单商品信息
                GoodsFree goodsFree = null;
                int status = 0;
                if (!preparePayOrder && "pay".equals(type)) {
                    goodsFree = iGoodsFreeService.selectByGoodsId(appOrderIntegral.getItemId());
                    ServerResponse<String> serverResponse = goodsFreeService.checkHaveBuy(appUser == null ? 0 : appUser.getUserId(), 1);
                    status = serverResponse.getStatus();
                }
                //如果是用户首单并且免单商品，记录免单状态-----并且不是预售订单
                boolean isGoodFree = (goodsFree != null && status == 515 && appUser != null && goodsFree.getNumber() > 0);
                if (isGoodFree) {
                    appOrderIntegral.setGoodFrees(1L);
                } else {
                    appOrderIntegral.setGoodFrees(0L);
                }
                //redis获取订单来源
                String s = addBuySource(appUser.getUserId(), appOrderIntegral.getItemId());
                appOrderIntegral.setBuySource(s);
                appOrderIntegral.setBindingTime(new Date());
                appOrderIntegral.setBinding(0);

                int i = iAppOrderIntegralService.insertAppOrderIntegral(appOrderIntegral);
                log.info(type + "订单{}入库-result={}", appOrderIntegral.getTradeId(), i);
//                if (i > 0 && appOrderIntegral.getGoodFrees() != null && appOrderIntegral.getGoodFrees() == 1) {
//                    //将订单次数加一的同时库存减一,将免单商品减去1
//                    int i1 = iGoodsFreeService.updateTotalOrdersByGoodsId(goodsFree.getId());
//                    log.info(type + "订单{}入库成功免单商品减一--i1={}", appOrderIntegral.getTradeId(), i1);
//                }
            } else {
                int i = iAppOrderIntegralService.insertAppOrderIntegral(appOrderIntegral);
                log.info(type + "订单{}入库-result={}", appOrderIntegral.getTradeId(), i);
            }
        }
        return appOrderIntegral;
    }

    /**
     * 判断是为预售订单
     *
     * @param appOrderIntegral
     * @return
     */
    public boolean isPreparePayOrder(AppOrderIntegral appOrderIntegral) {
        //判断是预售订单
        if (
                com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderIntegral.getTbDepositTime())
                        && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderIntegral.getTkDepositTime())
                        && !"--".equals(appOrderIntegral.getTkDepositTime())
                        && !"--".equals(appOrderIntegral.getTbDepositTime())
                        && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderIntegral.getDepositPrice())

        ) {
            return true;
        }
        return false;
    }


    /**
     * 判断是否是首购，绑定首单红包，免单不算首单
     *
     * @param userId
     * @param itemId
     * @param tradeId
     */
    public void firstPurchaseRedPacket(Long userId, Long itemId, Long tradeId) {
        //判断用户是否完成了首购
//        String isFistBuyRedPacket = redisTemplateService.getTByKey("firstPurchaseRedPacket" + "_" + userId, String.class);
//        if(!StringUtils.isEmpty(isFistBuyRedPacket)){
//            return;
//        }
        //如果未完成首购任务，那就先获取锁  (redis锁-时间 (10秒))
        long startTimes = System.currentTimeMillis() + 1000 * 60;
        if (!redisLockService.lock("user_order_first_task_lock_" + userId, startTimes + "")) {
            log.info("用户userid{}首购任务", userId);
            return;
        }
        //判断用户是否存在首购红包
        QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
        queryWrapper.eq("user_id", userId).eq("hb_type", 3).eq("hb_status", 1);
        AppUserRedReward appUserRedReward = IAppUserRedRewardService.getOne(queryWrapper);
        if (appUserRedReward == null) {
            return;
        }
        //判断红包是否过期
        AppUserRewardSetup rewardSetup = null;
        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
            rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
        } else {
            rewardSetup = appUserRewardSetupMapper.selectByPrimaryKey(1);
            redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60 * 60);
        }
        //任务红包没有起用过并且当前时间小于红包使用期限
        if ((System.currentTimeMillis() - appUserRedReward.getCreateTime()) < rewardSetup.getTaskRedMoneyInvalidTime() * 24L * 60 * 60 * 1000L) {

            long beforeSeconds = System.currentTimeMillis() / 1000 / 60 - 1;
            long seconds = System.currentTimeMillis() / 1000 / 60;
            int count = 0;
            //先从缓存中搜索记录
            String redisKeyStr = "AppUserSearchHistory_" + seconds;//当前分钟
            String key = "AppUserSearchHistory_" + beforeSeconds;//上一分钟
            if (redisTemplateService.hasKey(redisKeyStr)) {
                Map<String, String> searchMap = redisTemplateService.getMap(redisKeyStr, Map.class);
                String itemIds = searchMap.get(userId.toString());
                if (com.eco.fanliapp.utils.StringUtils.isNull(itemIds)) {
                    count = 0;
                } else {
                    count = 1;
                }
            }
            if (count == 0 && redisTemplateService.hasKey(key)) {
                Map<String, String> searchMap = redisTemplateService.getMap(key, Map.class);
                String itemIds = searchMap.get(userId.toString());
                if (com.eco.fanliapp.utils.StringUtils.isNull(itemIds)) {
                    count = 0;
                } else {
                    count = 1;
                }
            }
            if (count == 0) {
                //判断用户是否精准搜索过该商品
                QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
                searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", itemId);
                count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
            }

            if (count > 0) {
                //首次绑定订单，修改新人任务红包状态
                AppUserRedReward appUserRedRewardNew = new AppUserRedReward();
                appUserRedRewardNew.setTableId(appUserRedReward.getTableId());
                appUserRedRewardNew.setHbStatus(7);
                appUserRedRewardNew.setOrderId(tradeId);
                IAppUserRedRewardService.updateById(appUserRedRewardNew);
                //增加或修改任务日志及状态
                updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 3);
                //设置首购标识
                redisTemplateService.set("firstPurchaseRedPacket" + "_" + userId, "完成首购", 60 * 60 * 24);

            }
        }

    }

    /**
     * 获取商品信息
     *
     * @param itemId
     * @param order
     * @return
     */
    @Override
    public AppGoods getAppgoods(String itemId, AppOrderIntegral order) {

        AppGoods appGoods = null;
        try {
            appGoods = iAppGoodsService.findAppGoodsByItemId(itemId);
            if (appGoods == null) {
                HaoDanKuItemInfo haoDanKuItemInfo = taoBaoUtils.getHaoDanKuItemId(itemId);
                log.info("拉取商品不存在去好单库拉取商品结果{}--{}", order.getTradeId(), haoDanKuItemInfo == null ? null : haoDanKuItemInfo.getCode());
                if (haoDanKuItemInfo != null && haoDanKuItemInfo.getCode() == 1 && haoDanKuItemInfo.getData() != null) {
                    appGoods = new AppGoods();
                    HaoDanKuItemInfo.DataBean data = haoDanKuItemInfo.getData();
                    appGoods.setItempic(data.getItempic());
                    appGoods.setItemtitle(data.getItemshorttitle());
                    appGoods.setItemshorttitle(data.getItemshorttitle());
                    appGoods.setCouponmoney(Double.valueOf(data.getCouponmoney() == null ? "0" : data.getCouponmoney()));
                } else {
                    DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemId);
                    log.info("拉取商品不存在去大淘客拉取商品结果{}--{}", order.getTradeId(), dtkResponse == null ? null : dtkResponse.getCode());
                    if (dtkResponse != null && dtkResponse.getCode() == 1 && dtkResponse.getData() != null) {
                        DTKResponse.DataBean data = dtkResponse.getData();
                        appGoods = new AppGoods();
                        appGoods.setItempic(data.getMainPic());
                        appGoods.setItemtitle(data.getDtitle());
                        appGoods.setItemshorttitle(data.getDtitle());
                        appGoods.setCouponmoney(Double.valueOf(data.getCouponPrice() == null ? "0" : data.getCouponPrice()));
                    }
                }
                if (appGoods == null) {
                    try {
                        ServerResponse<List<TbkItemInfoGetInfo.NTbkItem>> response = taobaoService.getSearchItemIdDetail(itemId);
                        if (response != null && response.getStatus() == 200) {
                            for (TbkItemInfoGetInfo.NTbkItem item : response.getData()) {
                                appGoods = new AppGoods();
                                appGoods.setItempic(item.getPictUrl());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
            if (appGoods == null) {
                appGoods = new AppGoods();
            }
            if (com.eco.fanliapp.utils.StringUtils.isNull(appGoods.getItempic())) {
                appGoods.setItempic("http:" + order.getItemImg());
            }
            if (com.eco.fanliapp.utils.StringUtils.isNull(appGoods.getItemtitle())) {
                appGoods.setItemtitle(order.getItemTitle());
                appGoods.setItemshorttitle(order.getItemTitle());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询商品报错itmeid={}orderId={}", itemId, order.getTradeId());
        }
        return appGoods;
    }


    /**
     * 统一请求方法
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @param orderScene
     * @return
     */
    private String OrderMainNew(String session, String startTime, String endTime, long pageNo,
                                long tkStatus, long orderCountType, String orderQueryType, long orderScene, String positionIndex) {
        String str = "";
        TbkScOrderDetailsGetResponse tbkScOrderDetailsGetResponse = orderController.orderDetailsNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
        if (tbkScOrderDetailsGetResponse != null) {
            str = JSON.toJSONString(tbkScOrderDetailsGetResponse);
        }
        return str;
    }



    /**
     * 获取用户信息
     *
     * @param order
     * @return
     */
    private AppUser UserMainNew(TbkScOrderDetailsGetResponse.PublisherOrderDto order) {
        //先根据订单id去数据库中查询app_user_order表，存在再根据app_user_order表的user_id查询用户
        AppUser appUser = null;
        QueryWrapper<AppUserOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", order.getTradeId() + "");
        queryWrapper.eq("order_grade", 1);
        AppUserOrder appUserOrder = iAppUserOrderService.getOne(queryWrapper);
        if (appUserOrder != null && appUserOrder.getUserId() != null) {
            appUser = iAppUserService.selectAppUserByUserId(appUserOrder.getUserId());
        }
        if (appUser != null && appUser.getUserId() != null && appUser.getUserId() != 0) {
            return appUser;
        }

        //根据relation_id，SpecialId查询用户
        if (order.getRelationId() != null && order.getRelationId() != 0) {
            appUser = iAppUserService.selectUserInfoByRelationId(order.getRelationId());
        } else if (order.getSpecialId() != null && order.getSpecialId() != 0) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }

        //根据订单号查询
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            List<AppUserOrder> appUserOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
            if (!CollectionUtils.isEmpty(appUserOrders)) {
                for (AppUserOrder appUserOrder1 : appUserOrders) {
                    if (appUserOrder1 != null && appUserOrder1.getOrderGrade() != null && appUserOrder1.getOrderGrade() == 1) {
                        appUser = iAppUserService.selectAppUserByUserId(appUserOrder1.getUserId());
                    }
                }
            }
        }

        return appUser;
    }

    public String generateOrderDetailId(String childOrderId, String itemId) {
        return MD5Utils.createMD5(itemId + childOrderId);
    }

    /**
     * 统一接收类
     *
     * @param order
     * @return
     */
    private AppOrderIntegral OrderIntegralMainNew(TbkScOrderDetailsGetResponse.PublisherOrderDto order, AppUser appUser) {
        AppOrderIntegral appOrderIntegral = new AppOrderIntegral();
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            appUser = UserMainNew(order);
        }

        appOrderIntegral.setAdzoneId((order.getAdzoneId() == null ? "" : order.getAdzoneId()) + "");
        appOrderIntegral.setAdzoneName(order.getAdzoneName());
        appOrderIntegral.setAlipayTotalPrice(order.getAlipayTotalPrice());
        appOrderIntegral.setAuctionCategory(order.getItemCategoryName());
        appOrderIntegral.setClickTime(order.getClickTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getClickTime(), null));
        appOrderIntegral.setCommission(order.getTotalCommissionFee());
        appOrderIntegral.setCommissionRate(order.getTotalCommissionRate());
        appOrderIntegral.setEarningTime(order.getTkEarningTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTkEarningTime(), null));
        appOrderIntegral.setCreateTime(order.getTkCreateTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTkCreateTime(), null));
        appOrderIntegral.setItemId(order.getItemId());
        appOrderIntegral.setItemNum(order.getItemNum());
        appOrderIntegral.setItemTitle(order.getItemTitle());
        appOrderIntegral.setOrderDetailid(generateOrderDetailId(order.getTradeId(), order.getItemId().toString()));
        appOrderIntegral.setOrderType(order.getOrderType());
        appOrderIntegral.setPayPrice(order.getPayPrice());
        appOrderIntegral.setPayStatus(order.getTkStatus().toString());
        appOrderIntegral.setTkStatus(order.getTkStatus().intValue());
        appOrderIntegral.setRelationId(order.getRelationId());
        appOrderIntegral.setSellerNick(order.getSellerNick());
        appOrderIntegral.setSellerShopTitle(order.getSellerShopTitle());
        appOrderIntegral.setSiteId(order.getSiteId() == null ? "" : (order.getSiteId() + ""));
        appOrderIntegral.setSiteName(order.getSiteName());
        appOrderIntegral.setSpecialId(order.getSpecialId());
        appOrderIntegral.setTableCreateTime(System.currentTimeMillis());
        appOrderIntegral.setTableUpdateTime(System.currentTimeMillis());
        appOrderIntegral.setTaobaoUserId(appUser == null ? 0 : appUser.getTaobaoUserId());
        appOrderIntegral.setTotalCommissionFee(order.getTotalCommissionFee());
        appOrderIntegral.setTotalCommissionRate(order.getTotalCommissionRate());
        appOrderIntegral.setTradeId(Long.parseLong(order.getTradeId()));
        appOrderIntegral.setTradeParentId(Long.parseLong(order.getTradeParentId()));
        appOrderIntegral.setIncomeRate(order.getIncomeRate());
        appOrderIntegral.setPubSharePreFee(order.getPubSharePreFee());
        appOrderIntegral.setPrice(order.getItemPrice());
        appOrderIntegral.setSubsidyFee(order.getSubsidyFee());
        appOrderIntegral.setSubsidyRate(order.getSubsidyRate());
        appOrderIntegral.setSubsidyType(order.getSubsidyType());
        appOrderIntegral.setTk3rdPubId(order.getPubId());
//        appOrderDetail.setTk3rdType(order.getTk3rdType());
//        appOrderDetail.setTk3rdSiteid(order.getTk3rdSiteId());
//        appOrderDetail.setTk3rdAdzoneid(order.getTk3rdAdzoneId());
        appOrderIntegral.setTerminalType(order.getTerminalType());

        appOrderIntegral.setTkDepositTime(order.getTkDepositTime());
        appOrderIntegral.setTbDepositTime(order.getTbDepositTime());
        appOrderIntegral.setDepositPrice(order.getDepositPrice());
        appOrderIntegral.setAppKey(order.getAppKey());
        appOrderIntegral.setTkEarningTime(order.getTkEarningTime());
        appOrderIntegral.setTbPaidTime(order.getTbPaidTime());
        appOrderIntegral.setTkPaidTime(order.getTkPaidTime());
        appOrderIntegral.setRefundTag(order.getRefundTag() == null ? 0 : order.getRefundTag());
        appOrderIntegral.setItemImg(order.getItemImg());
        appOrderIntegral.setTkOrderRole(order.getTkOrderRole() == null ? 0 : order.getTkOrderRole());
        appOrderIntegral.setPubShareFee(order.getPubShareFee());
        appOrderIntegral.setPubShareRate(order.getPubShareRate());
        appOrderIntegral.setTkTotalRate(order.getTkTotalRate());
        appOrderIntegral.setAlimamaRate(order.getAlimamaRate());
        appOrderIntegral.setAlimamaShareFee(order.getAlimamaShareFee());
        appOrderIntegral.setFlowSource(order.getFlowSource());
        appOrderIntegral.setItemLink(order.getItemLink());
        appOrderIntegral.setTkCommissionPreFeeForMediaPlatform(order.getTkCommissionPreFeeForMediaPlatform());
        appOrderIntegral.setTkCommissionFeeForMediaPlatform(order.getTkCommissionFeeForMediaPlatform());
        appOrderIntegral.setTkCommissionRateForMediaPlatform(order.getTkCommissionRateForMediaPlatform());

        log.info("message订单佣金{}，计算后佣金{}", order.getPubSharePreFee(), BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        appOrderIntegral.setFanliMoney(BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        return appOrderIntegral;
    }



    public String addBuySource(Long userId, Long itemId) {
        //redis获取buy_source
        List<Map<Object, Object>> map = (List<Map<Object, Object>>) redisTemplate.opsForList().range("app_buy_source_" + userId, 0, -1);
        if (map.size() > 0) {
            List<String> orderSourceList = new ArrayList<>();
            for (Map orderSource : map) {
                if (orderSource.get("itemId").equals(itemId) && orderSource.get("jumpType") != null) {
                    orderSourceList.add(orderSource.get("jumpType").toString());
                }
            }
            String orderSourceStr = Joiner.on(",").join(orderSourceList);
            return orderSourceStr;
        }
        return null;
    }






    private CountLauncherPay countLauncherPay;

    private CountLauncherFail countLauncherFail;

    private CountLauncherSuccess countLauncherSuccess;

    private CountLauncherDone countLauncherDone;

    private CountLauncherRefund countLauncherRefund;

    @Override
    public CountLauncherPay getCountLauncherPay() {
        return countLauncherPay;
    }

    @Override
    public void setCountLauncherPay(CountLauncherPay countLauncherPay) {
        this.countLauncherPay = countLauncherPay;
    }


    @Override
    public void setCountLauncherFail(CountLauncherFail countLauncherFail) {
        this.countLauncherFail = countLauncherFail;
    }

    @Override
    public CountLauncherSuccess getCountLauncherSuccess() {
        return countLauncherSuccess;
    }

    @Override
    public void setCountLauncherSuccess(CountLauncherSuccess countLauncherSuccess) {
        this.countLauncherSuccess = countLauncherSuccess;
    }


    @Override
    public void setCountLauncherDone(CountLauncherDone countLauncherDone) {
        this.countLauncherDone = countLauncherDone;
    }


}
